package cn.edu.fzu.delivery.filter.impl;

import cn.edu.fzu.delivery.cache.NetworkCache;
import cn.edu.fzu.delivery.domain.entity.CourierDelivery;
import cn.edu.fzu.delivery.domain.entity.SysUser;
import cn.edu.fzu.delivery.domain.enums.DeliveryStatusEnum;
import cn.edu.fzu.delivery.filter.DeliveryFilter;
import cn.edu.fzu.delivery.filter.DeliveryFilterDto;
import cn.edu.fzu.delivery.handler.DeliverySession;
import cn.edu.fzu.delivery.service.CourierDeliveryService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 若发现有快递员派发的下一个网点与该快递派发的下一个网点相同，且还未派送，则将该快递分派给该快递员
 * 
 * @author fangxin
 * @date 2022/11/22
 */
@Component("sameDestinationFilter")
public class SameDestinationFilter implements DeliveryFilter {

    @Resource
    private NetworkCache           networkCache;
    @Resource
    private CourierDeliveryService courierDeliveryService;

    @Override
    public boolean prepare(DeliverySession session, DeliveryFilterDto dto) {

        //获取快递的派送路径
        List<Long> path = networkCache.getPath(session.getCurrentNetworkId(), session.getDestNetworkId());

        if (CollectionUtils.isEmpty(path)) {
            //路径为空则不触发该过滤器
            return false;
        }
        //获取下一个派送的网点id
        Long nextNetworkId = path.get(1);
        List<CourierDelivery> courierDeliveryList = courierDeliveryService.list(null, null, DeliveryStatusEnum.WAIT,
                nextNetworkId, null, null);

        if (CollectionUtils.isEmpty(courierDeliveryList)) {
            //如果没有快递员将前往派送网点，则不触发该过滤器
            return false;
        }
        List<Long> deliveryIdList = new ArrayList<>(courierDeliveryList.size());
        for (CourierDelivery courierDelivery : courierDeliveryList) {
            SysUser deliveryMan = courierDelivery.getDeliveryMan();
            if (!Objects.equals(deliveryMan.getNetwork().getId(), session.getCurrentNetworkId())) {
                //如果该快递员的不属于当前派件网点，则过滤该快递员
                continue;
            }
            deliveryIdList.add(deliveryMan.getId());
        }
        if (CollectionUtils.isEmpty(deliveryIdList)) {
            //如果当前派件网点没有快递员的派送地址为该快递的下一个目的网点，则不触发该过滤器
            return false;
        }
        dto.setSameDestDeliveryManList(deliveryIdList);
        return true;
    }


    @Override
    public boolean filter(SysUser user, DeliveryFilterDto dto) {
        //如果该快递员的派送的目的网点不是该快递的下一个派送网点，则过滤掉
        return !dto.getSameDestDeliveryManList().contains(user.getId());
    }
}
